package com.borya.dao.impl;

import com.borya.dao.MerchantFillServiceDAO;
import com.borya.framework.annotation.Component;
import com.borya.framework.core.ServerSqlSession;
import com.borya.model.db.MerchantInfoFill;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Component("merchantFillServiceDAO")
public class MerchantFillServiceDAOImpl extends BaseDAOImpl implements MerchantFillServiceDAO{

	
	private Logger log = Logger.getLogger(getClass());
	
	
	@Override
	public MerchantInfoFill getLast(final String merchantId) {
		try (ServerSqlSession session = getSqlDataSource().session();) {
			StringBuilder sql = new StringBuilder(256);
			sql.append("select id,order_id,regist_order_id,request_phone,user_id,dealer_id,merchant_id");
			sql.append(",company_name,address,store_address,merchant_type,sign_picture");
			sql.append(",door_picture_left,door_picture_right,hand_picture,business_licence");
			sql.append(",sign_merge_picture,user_name,city_code,city_name,create_time,order_status");
			sql.append(",audit_time,customer,merchant_id,gzt_check,head_picture,period,audit_type");
            sql.append(",auto_audit_desc,source_type,remarks,shop_address,shop_specific_address");
            sql.append(",identify_photo_front,identify_photo_reverse,identify_photo_hand,identify_photo_head");
			sql.append(" from tb_merchant_info_fill");
			sql.append(" where merchant_id=?  ");
			sql.append(" order by id  desc ");
			sql.append(" limit 1");
			return session.executeQuery(sql.toString(), rs-> {
				return cast(rs,merchantId);
			}, merchantId);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return null;
		}
	}
	
	@Override
	public MerchantInfoFill getByOrderId(String orderId) {
		try (ServerSqlSession session = getSqlDataSource().session();) {
			StringBuilder sql = new StringBuilder(256);
			sql.append("select id,order_id,regist_order_id,request_phone,user_id,dealer_id,merchant_id");
			sql.append(",company_name,address,store_address,merchant_type,sign_picture");
			sql.append(",door_picture_left,door_picture_right,hand_picture,business_licence");
			sql.append(",sign_merge_picture,user_name,city_code,city_name,create_time,order_status");
			sql.append(",audit_time,customer,merchant_id,gzt_check,head_picture,period,audit_type");
			sql.append(",auto_audit_desc,source_type,remarks,shop_address,shop_specific_address");
            sql.append(",identify_photo_front,identify_photo_reverse,identify_photo_hand,identify_photo_head");
			sql.append(" from tb_merchant_info_fill");
			sql.append(" where order_id=?  ");
			sql.append(" limit 1");
			return session.executeQuery(sql.toString(), rs-> {
				return cast(rs,orderId);
			}, orderId);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return null;
		}
	}

	private MerchantInfoFill cast(ResultSet rs,String param)throws SQLException{
		MerchantInfoFill merchant = new MerchantInfoFill();
		if (rs != null && rs.next()) {
			merchant.setOrderId(rs.getString("order_id"));
			merchant.setRegistOrderId(rs.getString("regist_order_id"));
			merchant.setRequestPhone(rs.getString("request_phone"));
			merchant.setUserId(rs.getString("user_id"));
			merchant.setDealerId(rs.getString("dealer_id"));
			merchant.setCompanyName(rs.getString("company_name"));
			merchant.setAddress(rs.getString("address"));
			merchant.setStoreAddress(rs.getString("store_address"));
			merchant.setMerchantType(rs.getInt("merchant_type"));
			merchant.setSignPicture(rs.getString("sign_picture"));
			merchant.setDoorPictureLeft(rs.getString("door_picture_left"));
			merchant.setDoorPictureRight(rs.getString("door_picture_right"));
			merchant.setHandPicture(rs.getString("hand_picture"));
			merchant.setBusinessLicence(rs.getString("business_licence"));
			merchant.setSignMergePicture(rs.getString("sign_merge_picture"));
			merchant.setUserName(rs.getString("user_name"));
			merchant.setCityCode(rs.getString("city_code"));
			merchant.setCityName(rs.getString("city_name"));
			merchant.setCreateTime(rs.getLong("create_time"));
			merchant.setOrderStatus(rs.getInt("order_status"));
			merchant.setAuditTime(rs.getLong("audit_time"));
			merchant.setCustomer(rs.getString("customer"));
			merchant.setMerchantId(rs.getString("merchant_id"));
			merchant.setGztCheck(rs.getString("gzt_check"));
			merchant.setHeadPicture(rs.getString("head_picture"));
			merchant.setPeriod(rs.getString("period"));
			merchant.setAuditType(rs.getInt("audit_type"));
			merchant.setAutoAuditDesc(rs.getString("auto_audit_desc"));
			merchant.setSourceType(rs.getInt("source_type"));
			merchant.setRemarks(rs.getString("remarks"));
            merchant.setShopAddress(rs.getString("shop_address"));
            merchant.setShopSpecificAddress(rs.getString("shop_specific_address"));
            merchant.setIdentifyPhotoFront(rs.getString("identify_photo_front"));
            merchant.setIdentifyPhotoReverse(rs.getString("identify_photo_reverse"));
            merchant.setIdentifyPhotoHand(rs.getString("identify_photo_hand"));
            merchant.setIdentifyPhotoHead(rs.getString("identify_photo_head"));
		}
		
		return merchant;
	}
	
	
	@Override
	public boolean insert(MerchantInfoFill infoFill) {
		StringBuilder sb = new StringBuilder(256);
		sb.append("insert into tb_merchant_info_fill set ");
		sb.append(" order_id='"+infoFill.getOrderId()+"'");
		sb.append(",regist_order_id='"+infoFill.getRegistOrderId()+"'");
		sb.append(",request_phone='"+infoFill.getRequestPhone()+"'");
		sb.append(",user_id='"+infoFill.getUserId()+"'");
		sb.append(",dealer_id='"+infoFill.getDealerId()+"'");
		sb.append(",company_name='"+infoFill.getCompanyName()+"'");
		sb.append(",address='"+infoFill.getAddress()+"'");
		sb.append(",store_address='"+infoFill.getStoreAddress()+"'");
		sb.append(",merchant_type="+infoFill.getMerchantType());
		sb.append(",sign_picture='"+infoFill.getSignPicture()+"'");
		sb.append(",door_picture_left='"+infoFill.getDoorPictureLeft()+"'");
		sb.append(",door_picture_right='"+infoFill.getDoorPictureRight()+"'");
		sb.append(",hand_picture='"+infoFill.getHandPicture()+"'");
		sb.append(",business_licence='"+infoFill.getBusinessLicence()+"'");
		sb.append(",sign_merge_picture='"+infoFill.getSignMergePicture()+"'");
		sb.append(",user_name='"+infoFill.getUserName()+"'");
		sb.append(",city_code='"+infoFill.getCityCode()+"'");
		sb.append(",city_name='"+infoFill.getCityName()+"'");
		sb.append(",create_time="+infoFill.getCreateTime());
		sb.append(",order_status="+infoFill.getOrderStatus());
		sb.append(",audit_time="+infoFill.getAuditTime());
		sb.append(",customer='"+infoFill.getCustomer()+"'");
		sb.append(",merchant_id='"+infoFill.getMerchantId()+"'");
		sb.append(",gzt_check='"+infoFill.getGztCheck()+"'");
		sb.append(",head_picture='"+infoFill.getHeadPicture()+"'");
		sb.append(",period='"+infoFill.getPeriod()+"'");
		sb.append(",audit_type="+infoFill.getAuditType());
		sb.append(",auto_audit_desc='"+infoFill.getAutoAuditDesc()+"'");
		sb.append(",source_type="+infoFill.getSourceType());
		sb.append(",remarks='"+infoFill.getRemarks()+"'");
		sb.append(",nickname='"+infoFill.getNickName()+"'");
        if (StringUtils.isNotBlank(infoFill.getShopAddress())) {
            sb.append(",shop_address='" + infoFill.getShopAddress() + "'");
        }
        if (StringUtils.isNotBlank(infoFill.getShopSpecificAddress())) {
            sb.append(",shop_specific_address='" + infoFill.getShopSpecificAddress() + "'");
        }
        if (StringUtils.isNotBlank(infoFill.getIdentifyPhotoFront())) {
            sb.append(",identify_photo_front='" + infoFill.getIdentifyPhotoFront() + "'");
        }
        if (StringUtils.isNotBlank(infoFill.getIdentifyPhotoReverse())) {
            sb.append(",identify_photo_reverse='" + infoFill.getIdentifyPhotoReverse() + "'");
        }
        if (StringUtils.isNotBlank(infoFill.getIdentifyPhotoHand())) {
            sb.append(",identify_photo_hand='" + infoFill.getIdentifyPhotoHand() + "'");
        }
		
		List<String> sql_list = new ArrayList<String>();
		sql_list.add(sb.toString());
		
		sb.delete(0, sb.length());
		sb.append("update tb_merchant set fill_status = 4 ");
		sb.append(" where merchant_id='"+infoFill.getMerchantId()+"'");
		sql_list.add(sb.toString());
		
		int[] result = executeBatch(sql_list);
		return (result != null && result.length > 0);
	}

	@Override
	public boolean updateStatus(MerchantInfoFill merchantInfoFill) {
		StringBuilder sb = new StringBuilder(256);
		sb.append("update tb_merchant_info_fill set");
		sb.append(" order_status ="+merchantInfoFill.getOrderStatus());
		sb.append(",auto_audit_desc='"+merchantInfoFill.getAutoAuditDesc()+"'");
		sb.append(" where order_id='"+merchantInfoFill.getOrderId()+"'");
		return executeUpdate(sb.toString());
	}

    @Override
    public boolean insertReplenishRecord(MerchantInfoFill infoFill) {
        StringBuilder sb = new StringBuilder(256);
        sb.append("insert into tb_merchant_replenish_record set ");
        sb.append(" order_id='" + infoFill.getOrderId() + "'");
        sb.append(",merchant_id='" + infoFill.getMerchantId() + "'");
        sb.append(",dealer_id='" + infoFill.getDealerId() + "'");
        sb.append(",company_name='" + infoFill.getCompanyName() + "'");
        sb.append(",addresses='" + infoFill.getAddresses() + "'");
        sb.append(",store_address='" + infoFill.getStoreAddress() + "'");
        sb.append(",sell_city_code='" + infoFill.getCityCode() + "'");
        sb.append(",sell_city_name='" + infoFill.getCityName() + "'");
        sb.append(",door_picture_out='" + infoFill.getDoorPictureOut() + "'");
        sb.append(",door_picture_in='" + infoFill.getDoorPictureIn() + "'");
        sb.append(",people_picture='" + infoFill.getPeoplePicture() + "'");
        sb.append(",merchant_type='" + infoFill.getMerchantType() + "'");
        sb.append(",create_time='" + infoFill.getCreateTime() + "'");
        sb.append(",order_status='" + infoFill.getOrderStatus() + "'");
        sb.append(",audit_type='" + infoFill.getAuditType() + "'");
        sb.append(",business_licence='" + infoFill.getBusinessLicence() + "'");
        sb.append(",period='" + infoFill.getPeriod() + "'");
        sb.append(",user_type_id='" + infoFill.getUserTypeId() + "'");
        sb.append(",user_type_name='" + infoFill.getUserTypeName() + "'");
        sb.append(",appType='" + infoFill.getAppType() + "'");
        sb.append(",user_id='" + infoFill.getUserId() + "'");
        sb.append(",door_picture_left='" + infoFill.getDoorPictureLeft() + "'");
        sb.append(",door_picture_right='" + infoFill.getDoorPictureRight() + "'");
        sb.append(",hand_picture='" + infoFill.getHandPicture() + "'");
        sb.append(",business_license_picture='" + infoFill.getBusinessLicensePicture() + "'");
        sb.append(",main_business='" + infoFill.getMainBusiness() + "'");

        List<String> sql = new ArrayList<>();
        sql.add(sb.toString());

        int[] result = executeBatch(sql);
        return (result != null && result.length > 0);
    }

    @Override
    public MerchantInfoFill getMerchantReplenishRecord(String merchantId, Integer orderStatus) {
        try (ServerSqlSession session = getSqlDataSource().session()) {
            StringBuilder sql = new StringBuilder(256);
            sql.append("select * from tb_merchant_replenish_record ");
            sql.append(" where merchant_id=? ");
            if (Objects.nonNull(orderStatus)) {
                sql.append(" and order_status = ").append(orderStatus);
            }
            sql.append(" limit 1 ");
            return session.executeQuery(sql.toString(), rs -> {
                MerchantInfoFill fill = new MerchantInfoFill();
                if (!Objects.isNull(rs) && rs.next()) {
                    fill.setOrderStatus(rs.getInt("order_status"));
                    fill.setAuditTime(rs.getLong("audit_time"));
                    fill.setRemarks(rs.getString("remarks"));
                    fill.setDoorPictureIn(rs.getString("door_picture_in"));
                    fill.setDoorPictureOut(rs.getString("door_picture_out"));
                    fill.setPeoplePicture(rs.getString("people_picture"));
                    fill.setCompanyName(rs.getString("company_name"));
                    fill.setAddresses(rs.getString("addresses"));
                    fill.setStoreAddress(rs.getString("store_address"));
                    fill.setCityCode(rs.getString("sell_city_code"));
                    fill.setCityName(rs.getString("sell_city_name"));
                    fill.setDoorPictureLeft(rs.getString("door_picture_left"));
                    fill.setDoorPictureRight(rs.getString("door_picture_right"));
                    fill.setBusinessLicensePicture(rs.getString("business_license_picture"));
                    fill.setHandPicture(rs.getString("hand_picture"));
                    fill.setMainBusiness(rs.getString("main_business"));
                    return fill;
                }
                return null;
            }, merchantId);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }
	
}
